import BasicConfig from "@/utils/config";
import Store from "@/store/index";
import { useGetTokenStorage } from "./useStorage";
import { uploadPath, uploadUrl } from "../utils/env";
import { useOpenLogin, useRefreshToken } from "./useLogin";
import errorCode from "../utils/http/errorCode";
import { eventBus } from "../enums/eventBus";
import encrypt from "../utils/encrypt";

/**
 * @description 删除图片(图片上传组件)
 */
export const useDeletePic = (event, list) => {
  list.splice(event.index, 1);
  return list;
};

/**
 * @description 选择图片
 * event
 * fileList
 * formData
 * key
 */
export const useAfterRead = async (params) => {
  const { event, fileList } = params;
  return new Promise(async (resovle, reject) => {
    // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
    let lists = [].concat(event.file);
    let fileListLen = fileList.length;
    lists.map((item) => {
      fileList.push({
        ...item,
        status: "uploading",
        message: "上传中",
      });
    });
    for (let i = 0; i < lists.length; i++) {
      const result = await useUploadFilePromise(lists[i].url, params);
      let item = fileList[fileListLen];
      fileList.splice(
        fileListLen,
        1,
        Object.assign(item, {
          status: "success",
          message: "",
          // url: result,
          file: result,
        })
      );
      fileListLen++;
    }
    resovle({
      data: fileList,
    });
  });
};

/**
 * @description 文件上传
 * @param {String} url 文件路径
 * @param {Object} formData
 */
export const useUploadFilePromise = (url, params) => {
  BasicConfig.loadToast("上传中...");
  const { formData, key = "uploadFile" } = params;
  console.log("上传url", url);
  const token = useGetTokenStorage();
  const { sign, timestamp, nonce } = encrypt(`${uploadPath}`, formData, "get");
  return new Promise((resolve, reject) => {
    let a = uni.uploadFile({
      url: uploadUrl,
      filePath: url,
      name: key,
      formData,
      header: {
        Authorization: token,
        device: "douyin",
        mode: "user",
        sign,
        timestamp,
        nonce,
      },
      success: async (uploadRes) => {
        const response = JSON.parse(uploadRes.data);
        if (response.code === errorCode.overToken) {
          const oldToken = useGetTokenStorage();
          // console.log("token过期.........oldToken:", oldToken);
          if (!oldToken) {
            // console.log("!!oldToken uni.$emit");
            uni.$emit(
              eventBus.login.popup,
              true,
              "请求拦截~overToken !!oldToken"
            );
          } else {
            await useRefreshToken();
            return useUploadFilePromise(url, params);
            // return new Promise((resolve) => {
            //   return useUploadFilePromise(url, params);
            // });
          }
        }
        resolve(response);
        // if (response.code === errorCode.success) {
        //   resolve(response);
        // }
        // else if (response.code === errorCode.overToken) {
        //   BasicConfig.toast(response.msg);
        //   useOpenLogin();
        // }
        // else {
        //   BasicConfig.toast(response.msg);
        // }
      },
      fail(err) {
        console.log("useUploadFilePromise err", err);
      },
      complete() {
        uni.hideLoading();
      },
    });
  });
};
